import cquery from '@dfeidao/atom-nodejs/db/complex-query';
import format from '@dfeidao/atom-nodejs/dt/format';
// import query from '@dfeidao/atom-nodejs/db/query';
import { IncomingHttpHeaders } from 'http';
import { systemid } from '../atom/config';

interface Message {
	filter: {
		teacher_no: string;
		auditor_status: string[];
		productid: string;
	};
	page_size: number;
	page_on: number;
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string[];
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}
interface I {
	class_id: string;
	student_no: string;
	start_time: number;
	start_times: string;
	finish_time: number;
	finish_times: string;
	student_name: string;
	submission_time: number;
	submission_times: string;
}
export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {

	const cq = cquery(action_id, session_id, systemid);
	// 1.依据 "教师编号" 查询<班级教师>表得到"班级编号",
	const class_teacher = await cq
		.add_field('class_teacher', 'class_id', 'class_id')
		.where_eq('class_teacher', 'teacher_no', message.filter.teacher_no)
		.where_eq('class_teacher', 'productid', message.filter.productid)
		.exec();
	// 2.班级编号
	const class_id = class_teacher.map((i: I) => {
		return i.class_id;
	});
	// 3.再依据"班级编号"查询<班级学生>表得到"学生编号"
	const class_student = await cq
		.add_field('class_student', 'student_no', 'student_no')
		.where_eq('class_student', 'productid', message.filter.productid)
		.where_in('class_student', 'class_id', class_id)
		.exec();
	// 4.得到"学生编号"
	const student_no = class_student.map((i: I) => {
		return i.student_no;
	});
	// 5.依据"学生编号","审核状态"="未审核"查询<学生请假>表
	const student_leave = await cq
		.add_field('student_leave', 'student_name', 'student_name')
		.add_field('student_leave', 'student_no', 'student_no')
		.add_field('student_leave', 'start_time', 'start_time')
		.add_field('student_leave', 'finish_time', 'finish_time')
		.add_field('student_leave', 'auditor_status', 'auditor_status')
		.add_field('student_leave', 'submission_time', 'submission_time')
		.add_field('student_leave', 'leave_num', 'leave_num')
		.where_eq('student_leave', 'productid', message.filter.productid)
		.where_in('student_leave', 'auditor_status', message.filter.auditor_status)
		.where_in('student_leave', 'student_no', student_no)
		.orderby_desc('submission_time')
		.page(message.page_size, message.page_on)
		.exec();
	student_leave.forEach((i: I) => {
		i.start_times = format(i.start_time, 'YYYY-MM-DD aa');
		i.finish_times = format(i.finish_time, 'YYYY-MM-DD aa');
		i.submission_times = i.submission_time ? format(i.submission_time, 'YYYY-MM-DD') : '';
		i.student_name = (i.student_name || '') + '提交的请假';
	});

	return { data: student_leave } as IWebResult;
}
